using System.IO;
using BitTorrent.Client.Peer.Exceptions;

namespace BitTorrent.Client.Peer.Message.Standard {
    internal class Piece : Request
    {
        public Piece() {
        }

        public Piece(BinaryReader reader, int length)
            : base(reader) {
            int blockLength = length - 13;

            if (blockLength <= 0) {
                throw new PeerMessageException("Can't create a piece with out block data.");
            }

            Block = new byte[blockLength];

            reader.Read(Block, 0, blockLength);
        }

        public byte[] Block { get; set; }

        public new byte[] GetMessage() {
            if (Block == null || Block.Length == 0) {
                throw new PeerMessageException("Can't create a piece message without a block use request or cancel instead.");
            }

            var result = GetMessage(PeerMessageId.Piece, (17 + Block.Length));

            using (var memory = new MemoryStream(result)) {
                var writer = new BinaryWriter(memory);
                writer.Seek(17, SeekOrigin.Begin); /// point where we want to append out block data

                writer.Write(Block);

                writer.Flush();
            }

            return result;
        }
    }
}